#!/usr/bin/env php
<?php

foreach ([__DIR__ . '/../../../autoload.php', __DIR__ . '/../vendor/autoload.php'] as $file) {
    if (file_exists($file)) {
        require $file;
        break;
    }
}

$argumentsProvider = new NdB\PhpDocCheck\ApplicationArgumentsProvider();
$arguments = $argumentsProvider->getArguments();

$outputChannels = array();
$cliChannel = new \NdB\PhpDocCheck\Output\Channels\Regular(new \SplFileObject('php://stdout'));
if($arguments['quiet']){
    $cliChannel = new \NdB\PhpDocCheck\Output\Channels\Quiet(new \SplFileObject('php://stdout'));
}
$outputChannels[] = $cliChannel;

if (!empty($arguments['reportFile'])) {
    $outputFile = new SplFileObject(getcwd(). '/' . $arguments['reportFile'], 'w');
    $outputChannels[] = new \NdB\PhpDocCheck\Output\Channels\Regular($outputFile);
}

$output_formats = array(
    'text'=>'\NdB\PhpDocCheck\Output\Formats\Text',
    'json'=>'\NdB\PhpDocCheck\Output\Formats\Json',
);

if (!array_key_exists($arguments['format'], $output_formats)) {
    $arguments['format'] = 'text';
}
$outputFormatter = new $output_formats[$arguments['format']]($outputChannels);

if ($arguments['help']) {
    $outputFormatter->out($arguments->getHelpText());
    exit;
}

$lexer = new \PhpParser\Lexer\Emulative(
    array(
        'usedAttributes' => array(
            'startLine',
            'comments',
        ),
    )
);

$parser = (new \PhpParser\ParserFactory)->create(
    \PhpParser\ParserFactory::PREFER_PHP7,
    $lexer
);

$analysisResults = array();
$fileFinder = new \NdB\PhpDocCheck\FileFinder();
$groupManager = new \NdB\PhpDocCheck\GroupManager($arguments->getOption('grouping-method'), $arguments->getOption('sorting-method'));
foreach ($fileFinder->getFiles($arguments) as $name => $object) {
    $file = new \NdB\PhpDocCheck\AnalysableFile(new SplFileInfo($name), $parser, $arguments, $groupManager);
    $result = $file->analyse();
    $outputFormatter->progress($result->getProgressIndicator());
    $analysisResults[] = $result;
}
$outputFormatter->progress("\n");

$outputFormatter->result($groupManager->getGroups());

if ($arguments['ignore-violations-on-exit']) {
    exit(0);
}
exit($outputFormatter->getExitCode($analysisResults));